import React from 'react';
import { Form, Input, Modal, message } from 'antd';
import { userService } from '../services/userService';
import { hashPassword } from '../utils/crypto';

const UserForm = ({ visible, onCancel, onSuccess, initialValues, mode = 'create' }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (visible && initialValues) {
      form.setFieldsValue(initialValues);
    }
  }, [visible, initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      // 如果有密码，进行加密处理
      if (values.password) {
        values.password = await hashPassword(values.password);
      }

      if (mode === 'create') {
        await userService.createUser(values);
        message.success('用户创建成功');
      } else {
        // 如果是编辑模式且没有修改密码，删除密码字段
        if (!values.password) {
          delete values.password;
        }
        await userService.updateUser(initialValues.id, values);
        message.success('用户更新成功');
      }

      form.resetFields();
      onSuccess();
    } catch (error) {
      console.error('表单提交错误:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={visible}
      title={mode === 'create' ? '创建用户' : '编辑用户'}
      okText={mode === 'create' ? '创建' : '更新'}
      cancelText="取消"
      confirmLoading={loading}
      onCancel={() => {
        form.resetFields();
        onCancel();
      }}
      onOk={handleSubmit}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: mode === 'create', message: '请输入密码' }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UserForm;